package com.bbcare.img.plat.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.bbcare.comm.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.img.plat.service.IImgMarkService;

/**
 * @name: 影像文件标记控制类
 * @author: DemonLee
 * @createTime: 2017.11.1
 * @description: 影像文件标记等操作
 * @modify:
 *
 */
@Controller
@RequestMapping("/imgMark")
public class ImgMarkController {
    private final Log logger = LogFactory.getLog(ImgMarkController.class);

    @Autowired
    private IImgMarkService imgMarkService;

    // 影像文件标记记录查询
    @ResponseBody
    @RequestMapping("/queryImgMarkRecord")
    public ResultModel<Object> queryImgMarkRecord(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in queryImgMarkRecord----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 入参信息校验
        Map<String, Object> chkVar = new HashMap<String, Object>();
        chkVar.put("imgId", "文件id");
        chkVar.put("userId", "患者id");
        ToolUtil.checkInputInfo("data", mapIn, chkVar);

        // 标记id列表校验
        chkVar.clear();
        List<Object> markIdList = ToolUtil.typeCast(mapIn.get("markIdList"));
        ToolUtil.checkInputList("markIdList", markIdList, chkVar);

        // 标记类型
        String markTypeFlag = (String) mapIn.get("markTypeFlag");
        if (StringUtils.isNotBlank(markTypeFlag)) {
            if ("0".equals(markTypeFlag)) {
                mapIn.put("markType", Constants.IMG_FILE_MARK_TEMPL_TYPE_FOR_FILE);
            } else if ("1".equals(markTypeFlag)) {
                mapIn.put("revMarkType", Constants.IMG_FILE_MARK_TEMPL_TYPE_FOR_FILE);
            } else {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        Constants.API_INPUT_PARAMS_DATA_ERROR + "，标记类型标志传值错误！"));
            }
        }

        // 登录信息
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));

        Map<String, Object> retMap = imgMarkService.listImgMarkRecord(mapIn);

        return new ResultModel<Object>(retMap);
    }

    // 影像文件标记记录详情查询
    @ResponseBody
    @RequestMapping("/queryImgMarkData")
    public ResultModel<Object> queryImgMarkData(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in queryImgMarkData----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 入参信息校验
        Map<String, Object> chkVar = new HashMap<String, Object>();
        chkVar.put("imgId", "文件id");
        chkVar.put("userId", "患者id");
        chkVar.put("markId", "标记id");
        ToolUtil.checkInputInfo("data", mapIn, chkVar);

        // 登录信息
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));

        Map<String, Object> retMap = imgMarkService.listImgMarkData(mapIn);

        return new ResultModel<Object>(retMap);
    }

    // 影像文件标记模板查询
    @ResponseBody
    @RequestMapping("/queryMarkTempl")
    public ResultModel<Object> queryMarkTempl(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in queryMarkTempl----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 入参信息校验
        Map<String, Object> chkVar = new HashMap<String, Object>();
        chkVar.put("equipId", "设备id");
        ToolUtil.checkInputInfo("data", mapIn, chkVar);

        // 病种id列表校验
        chkVar.clear();
        List<Object> diseaseIdList = ToolUtil.typeCast(mapIn.get("diseaseIdList"));
        ToolUtil.checkInputList("diseaseIdList", diseaseIdList, chkVar);

        // 标记类型
        String markTypeFlag = (String) mapIn.get("markTypeFlag");
        if (StringUtils.isNotBlank(markTypeFlag)) {
            if ("0".equals(markTypeFlag)) {
                mapIn.put("markType", Constants.IMG_FILE_MARK_TEMPL_TYPE_FOR_FILE);
            } else if ("1".equals(markTypeFlag)) {
                mapIn.put("revMarkType", Constants.IMG_FILE_MARK_TEMPL_TYPE_FOR_FILE);
            } else {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        Constants.API_INPUT_PARAMS_DATA_ERROR + "，标记类型标志传值错误！"));
            }
        }

        // 登录信息
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));

        Map<String, Object> retMap = imgMarkService.listMarkTempl(mapIn);

        return new ResultModel<Object>(retMap);
    }

    // 影像文件标记模板问卷内容查询
    @ResponseBody
    @RequestMapping("/queryMarkTemplCont")
    public ResultModel<Object> queryMarkTemplCont(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in queryMarkTemplCont----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 入参信息校验
        Map<String, Object> chkVar = new HashMap<String, Object>();
        chkVar.put("templId", "标记模板id");
        ToolUtil.checkInputInfo("data", mapIn, chkVar);
        chkVar.clear();
        chkVar.put("templVersion", "模板版本");
        ToolUtil.checkInputIntegerGe("data", mapIn, chkVar);

        // 登录信息
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("tenantId", sessionMap.get("tenantId"));

        Map<String, Object> retMap = imgMarkService.listMarkTemplCont(mapIn);

        return new ResultModel<Object>(retMap);
    }

    // 影像文件标记添加或修改
    @ResponseBody
    @RequestMapping("/saveImgMark")
    public ResultModel<Object> saveImgMark(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in saveImgMark----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        Map<String, Object> chkVar = new HashMap<String, Object>();
        Map<String, Object> chkInfo = ToolUtil.typeCast(mapIn.get("oprInfo"));
        chkVar.put("opCode", "操作编码");
        chkVar.put("opType", "操作类型");
        chkVar.put("opNote", "操作备注");
        ToolUtil.checkInputInfo("oprInfo", chkInfo, chkVar);
        chkInfo.put("updateTime", DateUtil.getSysDateA());
        chkInfo.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));

        // 文件信息校验
        chkVar.clear();
        chkInfo = ToolUtil.typeCast(mapIn.get("fileInfo"));
        chkVar.put("diseaseId", "病种id");
        chkVar.put("imgId", "文件id");
        chkVar.put("userId", "患者id");
        ToolUtil.checkInputInfo("fileInfo", chkInfo, chkVar);

        // 标记列表校验
        chkVar.clear();
        List<Object> markList = ToolUtil.typeCast(mapIn.get("markList"));
        this.checkSaveImgMark("markList", markList);

        // 登录信息
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("sessionInfo", sessionMap);

        Map<String, Object> retMap = imgMarkService.conductImgMark(mapIn);

        return new ResultModel<Object>(retMap);
    }

    // 影像文件标记添加或修改markList入参校验
    public void checkSaveImgMark(String checkNode, List<Object> markList) {
        ToolUtil.checkInputList(checkNode, markList, null);
        int m = 0;
        int msize = markList.size();
        Map<String, Object> markMap = new HashMap<String, Object>();
        Map<String, Object> checkVarString = new HashMap<String, Object>();
        Map<String, Object> checkVarInteger = new HashMap<String, Object>();
        Map<String, Object> checkVarInt = new HashMap<String, Object>();
        Map<String, Object> checkVarIntegerAll = new HashMap<String, Object>();
        Map<String, Object> checkValuesVar = new HashMap<String, Object>();
        List<Object> valuesList = new ArrayList<Object>();
        checkVarString.put("markName", "标记名称");
        checkVarString.put("templId", "标记模板id");
        checkVarString.put("markType", "标记类型");
        checkVarInteger.put("axisX", "标记区域左上角顶点距离左边距的距离");
        checkVarInteger.put("axisY", "标记区域左上角顶点距离上边距的距离");
        checkVarInteger.put("markHeight", "标记区域的高度");
        checkVarInteger.put("markWidth", "标记区域的宽度");
        checkVarIntegerAll.put("templVersion", "标记模板版本");
        checkValuesVar.put("dataId", "标记问题id");
        checkVarInt.put("rotationAngle", "文件旋转角度");
        for (m = 0; m < msize; m++) {
            markMap = ToolUtil.typeCast(markList.get(m));
            ToolUtil.checkInputInfo(checkNode, markMap, checkVarString);

            // 全文件标记不需要校验标记位置
            String markType = (String) markMap.get("markType");
            if (!Constants.IMG_FILE_MARK_TEMPL_TYPE_FOR_FILE.equals(markType)) {
                ToolUtil.checkInputIntegerGe(checkNode, markMap, checkVarInteger);
            }

            ToolUtil.checkInputIntegerGe(checkNode, markMap, checkVarIntegerAll);
            ToolUtil.checkInputIntegerNotNull(checkNode, markMap, checkVarInt);

            valuesList = ToolUtil.typeCast(markMap.get("values"));
            ToolUtil.checkInputList("values", valuesList, checkValuesVar);
        }

        return;
    }

    // 影像文件标记删除
    @ResponseBody
    @RequestMapping("/removeImgMark")
    public ResultModel<Object> removeImgMark(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in removeImgMark----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        Map<String, Object> chkVar = new HashMap<String, Object>();
        Map<String, Object> chkInfo = ToolUtil.typeCast(mapIn.get("oprInfo"));
        chkVar.put("opCode", "操作编码");
        chkVar.put("opType", "操作类型");
        chkVar.put("opNote", "操作备注");
        ToolUtil.checkInputInfo("oprInfo", chkInfo, chkVar);
        chkInfo.put("updateTime", DateUtil.getSysDateA());
        chkInfo.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));

        // 文件信息校验
        chkVar.clear();
        chkInfo = ToolUtil.typeCast(mapIn.get("markInfo"));
        chkVar.put("userId", "患者id");
        ToolUtil.checkInputInfo("markInfo", chkInfo, chkVar);

        // 标记id列表校验
        chkVar.clear();
        List<Object> markIdList = ToolUtil.typeCast(chkInfo.get("markIdList"));
        ToolUtil.checkInputList("markList", markIdList, null);

        // 登录信息
        Map<String, Object> sessionMap = ToolUtil.getSessionInfo(request);
        mapIn.put("sessionInfo", sessionMap);

        Map<String, Object> retMap = imgMarkService.eraseImgMark(mapIn);

        return new ResultModel<Object>(retMap);
    }

    // 获取文件访问url签名
    @ResponseBody
    @RequestMapping("/getImgFileSignUrl")
    public ResultModel<Object> getImgFileSignUrl(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in getImgFileSignUrl----arg==" + arg);

        // 基础校验
        ToolUtil.checkInputRoot(arg);

        JSONObject jsonArg = JSON.parseObject(arg);
        Map<String, Object> mapIn = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);

        // 操作信息校验
        Map<String, Object> chkVar = new HashMap<String, Object>();
        chkVar.put("imgId", "文件id");
        chkVar.put("imgUrl", "文件存放地址");
        List<Object> fileList = ToolUtil.typeCast(mapIn.get("fileList"));
        ToolUtil.checkInputList("fileList", fileList, chkVar);

        // 逐个获取签名
        int f = 0;
        int fsize = fileList.size();
        String imgNewUrl = "";
        String imgUrl = "";
        Map<String, Object> urlMap = new HashMap<String, Object>();
        for (f = 0; f < fsize; f++) {
            urlMap = ToolUtil.typeCast(fileList.get(f));
            imgUrl = (String) urlMap.get("imgUrl");
            imgNewUrl = OSSClientUtil.getFileSignUrl(imgUrl);
            if (StringUtils.isBlank(imgNewUrl)) {
                imgNewUrl = imgUrl;
            }
            urlMap.put("imgNewUrl", imgNewUrl);
        }

        return new ResultModel<Object>(mapIn);
    }
}
